<script type="text/javascript">
    $(function () {
                $('.phone').inputmask({
                    mask: '(*99[9]) 9999-9999',
                    definitions: {
                        '*': {
                            validator: "0",
                            cardinality: 1,
                            casing: "lower"
                        }
                    }
                });
                var reqId = $('#requestId').val();
                var requestDate = moment("${loanRequest.requestDate}");
                $("#requestDate").html(requestDate.format('YYYY/MM/DD'));
                var today = new Date();
                var birthday = $('#birthday').val();
                var age = 0;
                function Feedback(){}
                function Feedback (reqId, content, type, requireBack){
                    this.reqId = reqId;
                    this.content = content;
                    this.type = type;
                    this.require_back = requireBack;
                }

                function TalkRecord (reqId, content, number){
                    this.reqId = reqId;
                    this.content = content;
                    this.number = number;
                }
                if (birthday) {
                    age = today.getYear() - new Date(birthday).getYear();
                    $('#age').val(age);
                }
                $('.datepicker').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    dateFormat: "mm/dd/yy",
                    defaultDate: "-18y",
                    maxDate: "-18y",
                    minDate: "-100y",
                    "yearRange":"1930:-17"
                });

                var loanDatepicker = $('#loanDate').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    dateFormat: "mm/dd/yy",
                    defaultDate: "+2d",
                    maxDate: "+1y",
                    minDate: "-1y",
                    "yearRange":"+0:+1"
                });

        $('.datepicker2').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: "mm/dd/yy",
            defaultDate: "+0d",
            maxDate: "+20y"
        });

                $('#approveMoney').click(function () {
                    if ($('input.insure[type=checkbox]:not(:checked)').length>0){
                        alert("<fmt:message key="insurenceNotDoneMsg"/>");
                        return false;
                    }
                });

                var feedbackTable = $('#feedbackList').DataTable({
                    /*"language": {
                     "url": "//cdn.datatables.net/plug-ins/1.10.7/i18n/Chinese.json"
                     },
                     "ajax": {
                     url: "/loanRequests/feedbacks?reqId="+ reqId,
                     "dataSrc": ""
                     },
                     "columns": [
                     { "title": "<fmt:message key="feedback.time"/>",data: "time", type: 'date',"mRender": function (data, type, full) {
                     var dtStart = new Date(data);
                     var dtStartWrapper = moment(dtStart);
                     return dtStartWrapper.format('YYYY/MM/DD');
                     } },
                     { "title": "<fmt:message key="feedback.operator"/>",data: "operator" },
                     { "title": "<fmt:message key="feedback.content"/>", data: "content"},
                     { "title": "<fmt:message key="feedback.reqStatus"/>", data: "readableStatus"}
                     ],*/
                    "scrollY":"150px",
                    "scrollCollapse": true,
                    "paging":  false,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bAutoWidth": true,
                    "info": false,
                    "order": [[ 0, "desc" ]],
                    "bSort": true
                });
                var talkRecordTable = $('#talkRecordList').DataTable({
                    /*"language": {
                     "url": "//cdn.datatables.net/plug-ins/1.10.7/i18n/Chinese.json"
                     },
                     "ajax": {
                     url: "/loanRequests/talkrecords?reqId="+ reqId,
                     "dataSrc": ""
                     },
                     "columns": [
                     { "title": "<fmt:message key="feedback.time"/>",data: "time", type: 'date',"mRender": function (data, type, full) {
                     var dtStart = new Date(data);
                     var dtStartWrapper = moment(dtStart);
                     return dtStartWrapper.format('YYYY/MM/DD');
                     } },
                     { "title": "<fmt:message key="feedback.operator"/>",data: "operator" },
                     { "title": "<fmt:message key="feedback.content"/>", data: "content"},
                     {"title": '<fmt:message key="user.phoneNumber"/>', data: "number"}
                     ],*/
                    "scrollY":"150px",
                    "scrollCollapse": true,
                    "paging":         false,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bAutoWidth": false,
                    "info": false,
                    "order": [[ 0, "desc" ]],
                    "bSort": true
                });
                var dialogFeedback;

                dialogFeedback = $( "#feedback" ).dialog({
                    autoOpen: false,
                    height: 500,
                    width: 550,
                    modal: true
                });

        var dialogReplyFeedback;

        dialogReplyFeedback = $( "#feedbackReply" ).dialog({
            autoOpen: false,
            height: 500,
            width: 550,
            modal: true
        });

                $( "#open-feedback" ).click(function() {
                    $("#feedbackContent").val('');
                    $("#replyFeedBack").val('');
                    $("#requireBack").prop("disabled", false);
                    dialogFeedback.dialog( "open" );
                });
        $( ".needReply" ).click(function() {
            $("#feedbackContent").val('');
            var feedbackId = $(this).attr("id");
            $("#replyFeedBack").val(feedbackId);
            $("#feedbackContentOrg").val($(this).parent().prevAll().eq(1).html());
            document.fromElement=$(this).parent();
            dialogReplyFeedback.dialog( "open" );
        });
        $(".markRead").click(function(){
            var ele = $(this).parent();
            $.ajax("/loanRequests/feedback/read?reqId="+reqId+"&feedBackId="+$(this).attr("id")).done(function(data){
                ele.html('<fmt:message key="FEEDBACK_STATUS_End"/>');
            })
        })

        $("input[name=feedbackType]").click(function(){
            if ($("input[name=feedbackType]:checked").val() == 'MaterialType'){
                $("#requireBack").prop("checked", true);
                $("#requireBack").prop("disabled", true);
            } else{
                $("#requireBack").prop("checked", false);
                $("#requireBack").prop("disabled", false);
            }
        })
                $("#saveFeedback").click(function(){
                    var requireBack = $("#requireBack:checked").length>0 ? true:false;
                    if (!$("#feedbackContent").val()){
                        alert('<fmt:message key="feedback.validate"/>');
                        return false;
                    } else {
                        var feedback = new Feedback(reqId,$("#feedbackContent").val(),$("input[name=feedbackType]:checked").val(), requireBack );
                        if($("#replyFeedBack").val()!=null){
                            feedback.feedBackId = $("#replyFeedBack").val();
                        }
                        $("#feedbackOverlay").attr("style", "")
                        $.ajax("/loanRequests/feedbacks", {
                            method: 'POST',
                            data: feedback,
                            success: function (data){
                                if(data.id!=$("#replyFeedBack").val()){
                                    $("#feedbackOverlay").attr("style", "display:none");
                                    dialogFeedback.dialog("close");
                                    feedbackTable.row.add( [
                                        data.time,
                                        data.operator,
                                        feedback.content.length>10?feedback.content.substr(0,10):feedback.content,
                                        data.feedbackType
                                    ] ).draw();
                                }
//
//                                feedbackTable.ajax.reload(function(){
//                                 $("#feedbackOverlay").attr("style", "display:none")
//                                 });
                            }
                        })
                    }
                });
        $("#saveFeedbackReply").click(function(){
            var requireBack = false;
            if (!$("#feedbackContentNew").val()){
                alert('<fmt:message key="feedback.validate"/>');
                return false;
            } else {
                var content = $("#feedbackContentOrg").val() + '\n -----' + $("#feedbackContentNew").val()
                var feedback = new Feedback(reqId,content,"", requireBack );
                    feedback.feedBackId = $("#replyFeedBack").val();
                $("#feedbackOverlay").attr("style", "")
                $.ajax("/loanRequests/feedbacks", {
                    method: 'POST',
                    data: feedback,
                    success: function (data){
                        $("#feedbackOverlay").attr("style", "display:none");
                        dialogReplyFeedback.dialog("close");
                        document.fromElement.html('<fmt:message key="FEEDBACK_STATUS_Returned"/>');
                        document.fromElement.prevAll().eq(1).html(content);
                    }
                })
            }
        });
                $("#saveTalkRecord").click(function(){
                    if (!$("#talkrecordContent").val()){
                        alert('<fmt:message key="talkrecord.validate"/>');
                        return false;
                    } else {
                        var talkRecord = new TalkRecord(reqId,$("#talkrecordContent").val(), $("#talkPhoneNumber").val() );
                        $("#talkOverlay").attr("style", "");
                        $.ajax("/loanRequests/talkrecords", {
                            method: 'POST',
                            data: talkRecord,
                            success: function (data){
                                $("#talkOverlay").attr("style", "display:none");
                                dialogTalk.dialog("close");
                                talkRecordTable.row.add( [
                                    data.time,
                                    data.operator,
                                    talkRecord.content.length>10?talkRecord.content.substr(0,10):talkRecord.content,
                                    talkRecord.number
                                ] ).draw();
                                /*talkRecordTable.ajax.reload(function(){
                                 $("#talkOverlay").attr("style", "display:none")
                                 });*/
                            }
                        })
                    }
                });

                var dialogSuggest;
                dialogSuggest = $('#suggest').dialog({
                    autoOpen: false,
                    height: 400,
                    width: 550,
                    modal: true
                });
                $( "#open-suggest" ).click(function() {
                    $.ajax("/loanRequests/getLoanRequest?reqId="+reqId, {
                        success: function(data){
                            $("#dealerComment").val(data.dealerComment);
                            $("#auditComment").val(data.auditComment);
                            dialogSuggest.dialog( "open" );
                        }
                    })
                });

                function Approval(reqId, dealerComment, auditComment){
                    this.reqId = reqId;
                    this.dealerComment = dealerComment;
                    this.auditComment = auditComment;
                }

                var dialogDecide;
                dialogDecide = $('#decide').dialog({
                    autoOpen: false,
                    height: 600,
                    width: 550,
                    modal: true
                });
                $( "#open-decide" ).click(function() {
                    dialogDecide.dialog( "open" );
                });

                var dialogTalk;
                dialogTalk = $('#talk').dialog({
                    autoOpen: false,
                    height: 500,
                    width: 550,
                    modal: true
                });
                $( "#open-talk" ).click(function() {
                    $("#talkrecordContent").val('');
                    var userType = $("#talkPerson").val();
                    var phoneType = $("#talkPhoneType").val();
                    getPhoneNumber(userType, phoneType);
                    dialogTalk.dialog( "open" );
                });

                function getPhoneNumber(userType, phoneType) {
                    var number='';
                    if (userType == "mainPerson"){
                        switch(phoneType){
                            case "mobileNo":
                                number=$("#mobileNo").val();
                                break;
                            case "homeTelNo":
                                number=$("#homeTelNo").val();
                                break;
                            case "workTelNo":
                                number=$("#workTelNo").val();
                                break;
                            default:
                                break;
                        }
                    } else if(userType == "coPerson"){
                        switch(phoneType){
                            case "mobileNo":
                                number=$("#coMobileNo").val();
                                break;
                            case "homeTelNo":
                                number=$("#coHomeTelNo").val();
                                break;
                            case "workTelNo":
                                number=$("#coWorkTelNo").val();
                                break;
                            default:
                                break;
                        }
                    } else if(userType == "dbPerson"){
                        switch(phoneType){
                            case "mobileNo":
                                number=$("#dbMobileNo").val();
                                break;
                            case "homeTelNo":
                                number=$("#dbHomeTelNo").val();
                                break;
                            case "workTelNo":
                                number=$("#dbWorkTelNo").val();
                                break;
                            default:
                                break;
                        }
                    } else if(userType == "dealer"){
                        number=$("#dealer_phone").html();
                    } else if (userType == "urgent1"){
                        number=$("#urgentContactTelNo1").val();
                    }else if (userType == "urgent2"){
                        number=$("#urgentContactTelNo2").val();
                    }else if (userType == "urgent3"){
                        number=$("#urgentContactTelNo3").val();
                    }else if(userType == "others"){
                        number="";
                    }
                    $("#talkPhoneNumber").val(number);
                }

                $("#talkPhoneType").change(function(){
                    var userType = $("#talkPerson").val();
                    var phoneType = $("#talkPhoneType").val();
                    getPhoneNumber(userType, phoneType);
                });
                $("#talkPerson").change(function(){
                    var userType = $("#talkPerson").val();
                    var phoneType = $("#talkPhoneType").val();
                    getPhoneNumber(userType, phoneType);
                })

                var dialogApprovalHistory;
                dialogApprovalHistory = $('#approvalHistory').dialog({
                    autoOpen: false,
                    height: 600,
                    width: 550,
                    modal: true
                });
                $( "#open-approvalHistory" ).click(function() {
                    dialogApprovalHistory.dialog( "open" );
                });

                var activityTable = $('#activityList').DataTable({
                    /*"language": {
                     "url": "//cdn.datatables.net/plug-ins/1.10.7/i18n/Chinese.json"
                     },
                     "ajax": {
                     url: "/loanRequests/activities?reqId="+ reqId,
                     "dataSrc": ""
                     },
                     columns: [
                     { "title": "<fmt:message key="feedback.time"/>",data: "time", type: 'date',"mRender": function (data, type, full) {
                     var dtStart = new Date(data);
                     var dtStartWrapper = moment(dtStart);
                     return dtStartWrapper.format('DD/MM/YYYY HH:mm');
                     } },
                     { "title": "<fmt:message key="feedback.operator"/>",data: "operator" },
                     { "title": "<fmt:message key="feedback.content"/>", data: "activity"}
                     ],*/
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bSort": false,
                    "bInfo": false,
                    "bAutoWidth": false
                });

                var dialogRelated;
                dialogRelated = $('#related').dialog({
                    autoOpen: false,
                    height: 500,
                    width: 800,
                    modal: true,
                    close: function() {
                        document.ruleUrl='';
                    }
                });
                $( ".open-related" ).click(function() {
                    document.ruleUrl = $(this).parent().prev().val();
                    relatedTable.ajax.url(document.ruleUrl);
                    relatedTable.ajax.reload();
                    dialogRelated.dialog( "open" );
                });

                var relatedTable = $('#relatedList').DataTable({
                    "language": {
                        "url": "//cdn.datatables.net/plug-ins/1.10.7/i18n/Chinese.json"
                    },
                    "ajax": {
                        "url": "xxxx",
                        "dataSrc": ""
                    },
                    columns: [
                        { "title": "<fmt:message key="loanRequest.number"/>", data: "number", "mRender": function (data, type, full) {
                            return '<a target="_blank" href="loanRequestform?reqId='+ full.id + '"> '+data+ '</a>';
                        }},
            { "title": "<fmt:message key="loanRequest.mainApplicant"/>",data: "name" },
    { "title": "<fmt:message key="loanRequest.dealer"/>", data: "dealer"},
    {"title": "<fmt:message key="loanRequest.vehicleModel"/>", data: "vehicle"},
    {"title": "<fmt:message key="loanRequest.loanAmount"/>", data: "loanAmount"},
    {"title": "<fmt:message key="loanRequest.status"/>", data: "status"},
    {"title": "<fmt:message key="loanRequestDetail.relatedRecordContent"/>", data: "content"}
    ],
    "bPaginate": false,
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": false,
            "bAutoWidth": false
    });

    var dialogHistory;
    dialogHistory = $('#history').dialog({
        autoOpen: false,
        height: 500,
        width: 800,
        modal: true,
        close: function() {
            document.ruleUrl='';
        }
    });
    $( ".open-history" ).click(function() {
        document.ruleUrl = $(this).parent().prev().val();
        historyTable.ajax.url(document.ruleUrl);
        historyTable.ajax.reload();
        dialogHistory.dialog( "open" );
    });

    var historyTable = $('#historyList').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.7/i18n/Chinese.json"
        },
        "ajax": {
            "url": "xxxx",
            "dataSrc": ""
        },
        columns: [
            { "title": "<fmt:message key="loanRequest.number"/>", data: "number", "mRender": function (data, type, full) {
                return '<a target="_blank" href="loanRequestform?reqId='+ full.id + '"> '+data+ '</a>';
            }},
    { "title": "<fmt:message key="loanRequest.mainApplicant"/>",data: "name" },
    { "title": "<fmt:message key="loanRequest.dealer"/>", data: "dealer"},
    {"title": "<fmt:message key="loanRequest.vehicleModel"/>", data: "vehicle"},
    {"title": "<fmt:message key="loanRequest.loanAmount"/>", data: "loanAmount"},
    {"title": "<fmt:message key="loanRequest.status"/>", data: "status"}
    ],
    "bPaginate": false,
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": false,
            "bAutoWidth": false
    })
        var dialogCreditInfo = $( "#creditInfo" ).dialog({
            autoOpen: false,
            height: 600,
            width: 550,
            modal: true
        });

        $( "#open-creditInfo" ).click(function() {
            dialogCreditInfo.dialog( "open" );
        });



    });

</script>